<template>
	<view class="content">
		<!-- 顶部背景 -->
		<view class="tang-feng-bg"></view>

		<!-- 内容区 -->
		<view class="tang-feng-block">
			<!-- 用户数据块 -->
			<view class="tang-feng-data">
				<!-- 订单状态 -->
				<view class="detail-top">
					<view class="detail-top-1">
						<image src="/static/detail/jinxi.png" mode="widthFix"></image>
						<view class="detail-top-1" v-for="item in orderStatusDict">
							<text v-if="orderDetail.orderStatus == item.dictValue"> {{item.dictLabel}}</text>
							<!-- 订单状态与字典值原因则直接显示匹配到的字典的文本 -->
						</view>
					</view>
					<view class="detail-top-2">
						<text>{{ statusHintText }}</text>
					</view>
				</view>

				<!-- 用户/地址信息 -->
				<view class="detailitem detail-address">
					<view style="flex: 1; margin:auto;">
						<image src="/static/detail/address.png"></image>
					</view>
					<view>
						<view class="top">
							<input class="input-item" placeholder="请输入收货人姓名" v-model="orderDetail.receiverName"
								:readonly="isReadOnly" :disabled="isReadOnly" />
							<input class="input-item" placeholder="请输入收货人电话" v-model="orderDetail.receiverPhone"
								type="number" maxlength="11" :readonly="isReadOnly" :disabled="isReadOnly" />
							<textarea class="address-textarea" placeholder="请输入收货地址"
								placeholder-class="placeholder-style" v-model="orderDetail.receiverAddress" auto-height
								:readonly="isReadOnly" :disabled="isReadOnly" />
						</view>
					</view>
				</view>

				<!-- 商品信息 -->
				<view class="detailitem shopBox">
					<view class="item" v-for="(detail,index) in orderDetail.detailsList" :key="index">
						<image :src="imagePrefix+detail.dishImage" mode="widthFix"
							style="width: 140rpx; height:140rpx;"></image>
						<view class="conBox">
							<view class="conBox-1">{{detail.dishName}}</view>
							<view class="conBox-3">¥ {{detail.dishPrice}}</view>
						</view>
						<view class="number">x{{detail.quantity}}</view>
					</view>
				</view>

				<!-- 订单信息 -->
				<view class="detailitem orderItem">
					<view class="orderItem-min">
						<view class="orderItem-1">订单编号：</view>
						<view class="orderItem-2">{{orderDetail.orderNo}}</view>
						<view class="orderItem-3" @click="copyText(orderDetail.orderNo)">复制</view>
					</view>
					<view class="orderItem-min">
						<view class="orderItem-1">下单时间：</view>
						<view class="orderItem-2">{{orderDetail.createTime}}</view>
					</view>

					<!-- 配送方式 -->
					<view class="orderItem-min">
						<view class="orderItem-1">配送方式：</view>
						<picker class="orderItem-2" mode="selector" :range="deliveryMethods" range-key="dictLabel"
							:value="selectedDeliveryIndex" @change="handleDeliveryMethodChange" :disabled="isReadOnly">
							<view>
								{{ deliveryText }}
								<image v-if="!isReadOnly" src="../../static/edit.png"
									style="width: 36rpx;height: 30rpx; margin-left: 20rpx;"></image>
							</view>
						</picker>
					</view>

					<!-- 预计送达时间 -->
					<view class="orderItem-min">
						<view class="orderItem-1">预计送达：</view>
						<picker class="orderItem-2" mode="selector" :range="timeSlots" :value="selectedTimeSlotIndex"
							@change="handleTimeSlotChange" :disabled="!showTimeEditIcon || isReadOnly">
							<view>{{ selectedTimeSlotText || '请选择送达时间' }}
								<image v-if="showTimeEditIcon && !isReadOnly" src="../../static/edit.png" style="width: 32rpx; height: 30rpx; margin-left: 20rpx;" />
							</view>
						</picker>
					</view>

					<!-- 餐具数量 -->
					<view class="orderItem-min">
						<view class="orderItem-1">餐具数量：</view>
						<view v-for="(item, index) in tablewareStatus" :key="index"
							@click="!isReadOnly && handleTablewareStatusChange(item.dictValue)"
							:class="['custom-radio', orderDetail.tablewareStatus == item.dictValue ? 'checked' : '', isReadOnly ? 'disabled' : '']">
							<view class="radio-icon"></view>
							<text>{{ item.dictLabel }}</text>
						</view>
					<!-- 	<radio-group class="orderItem-2">
							<view class="radio-container">
								<label class="radio-label" v-for="(item, index) in tablewareStatus" :key="index"
									@click="handleTablewareStatusChange(item.dictValue)">
									<radio :value="item.dictValue"
										:checked="orderDetail.tablewareStatus == Number(item.dictValue)" color="#07C160"
										:disabled="isReadOnly" />
									<text>{{ item.dictLabel }}</text>
								</label>
							</view>
						</radio-group> -->
					</view>

					<!-- 餐具数量输入 -->
					<view class="orderItem-min" v-if="showTablewareQuantityInput">
						<view class="orderItem-1">填写餐具数量份数:</view>
						<input class="orderItem-2" placeholder="请输入需要的餐具数量" min="1" max="10" type="number"
							v-model="orderDetail.tablewareNumber" :disabled="isReadOnly" />
					</view>

					<!-- 留言备注 -->
					<view class="orderItem-min">
						<view class="orderItem-1">留言备注</view>
						<textarea class="orderItem-2" placeholder="请输入留言备注（选填）" v-model="orderDetail.remark" auto-height
							:readonly="isReadOnly" :disabled="isReadOnly" />
					</view>
				</view>

				<!-- 订单费用信息 -->
				<view class="detailitem orderItem" style="margin-bottom: 100rpx;">
					<view class="orderItem-min orderInfo">
						<view class="orderItem-1">商品总额</view>
						<view class="orderItem-2">¥ {{orderDetail.totalAmount}}</view>
					</view>
					<view class="orderItem-min orderInfo">
						<view class="orderItem-1">打包费</view>
						<view class="orderItem-2">+ ¥{{orderDetail.packAmount}}</view>
					</view>
					<view class="orderItem-min orderInfo">
						<view class="orderItem-1">运费</view>
						<view class="orderItem-2">+ ¥{{orderDetail.freightAmount}}</view>
					</view>
					<view class="orderItem-min orderInfo" style="border-bottom: 2rpx solid rgba(0,0,0,0)">
						<view class="orderItem-1"></view>
						<view class="orderItem-2">实付款：<text style="color: red;"> ¥{{orderDetail.paymentAmount}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottomBox" v-if="showPayButton">
			<view class="leftTxt">¥<text
					style="font-size: 46rpx;margin-left: 15rpx;">{{orderDetail.paymentAmount}}</text></view>
			<view class="gnBox">
				<view class="item lianxi" @click="submit">支付</view>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		getUserOrdersInfo,
		getOrdersById,
		updateOrders
	} from '@/api/system/orders.js'
	import {
		getDicts
	} from '@/api/system/dict/data.js'
	import Alert from '@/utils/alert';

	export default {
		data() {
			return {
				imagePrefix: this.$imagePrefix,
				orderStatusDict: [], // 订单状态字典数据
				orderDetail: {
					detailsList: [],
					tablewareStatus: 1 // 默认值
				},
				deliveryMethods: [], // 配送方式
				selectedDeliveryIndex: 0,
				showTimeEditIcon: false,
				timeSlots: [], // 时间段列表
				selectedTimeSlotIndex: -1,
				selectedTimeSlotText: "",
				currentTime: new Date(),
				timeRanges: [], // 存储实际的时间范围
				tablewareStatus: [], // 餐具状态
				isReadOnly: false,
				nav_opacity: 'rgba(255,255,255,0)',
				fontColor: '#ffffff'
			}
		},

		computed: {
			// 状态提示文本
			statusHintText() {
				const status = this.orderDetail.orderStatus;
				const hints = {
					'0': '请尽快支付订单哦！超过12小时将自动取消',
					'1': '请耐心等待！',
					'2': '食堂阿姨正在制作打包中，请耐心等待！',
					'3': '请耐心等待，待配送员取货！',
					'4': '请耐心等待！',
					'5': '欢迎再次选购！'
				};
				return hints[status] || '';
			},

			// 配送方式文本
			deliveryText() {
				return this.deliveryMethods[this.selectedDeliveryIndex]?.dictLabel || '立即配送';
			},

			// 是否显示餐具数量输入框
			showTablewareQuantityInput() {
				return this.orderDetail.tablewareStatus === 2;
			},

			// 是否显示支付按钮
			showPayButton() {
				return this.orderDetail.orderStatus === 0 && !this.isReadOnly;
			}
		},

		onLoad(options) {
			const {
				orderId,
				readonly = 'false'
			} = options;
			this.isReadOnly = readonly === 'true';

			Promise.all([
				this.getDictsOrderStatus("order_status"),
				this.getDictsTableware("tableware_status"),
				this.getOrdersDetails(orderId)
			]).then(() => {
				this.checkReadOnlyMode();
			});
		},

		methods: {
			// 获取订单状态字典数据
			async getDictsOrderStatus(value) {
				try {
					const res = await getDicts(value);
					this.orderStatusDict = res.data;
				} catch (error) {
					console.error('获取订单状态字典失败:', error);
				}
			},

			// 获取订单详情
			async getOrdersDetails(orderId) {
				try {
					const res = await getOrdersById(orderId);
					this.orderDetail = res.data;

					// 获取配送方式字典
					const deliveryRes = await getDicts("delivery_status");
					this.deliveryMethods = deliveryRes.data;

					// 设置默认配送方式
					const defaultDeliveryIndex = this.deliveryMethods.findIndex(
						item => item.dictValue === this.orderDetail.deliveryStatus
					);
					this.selectedDeliveryIndex = defaultDeliveryIndex !== -1 ? defaultDeliveryIndex : 0;

					// 初始化时间段
					this.$nextTick(() => {
						const date = this.orderDetail.estimatedDeliveryTime ?
							new Date(this.orderDetail.estimatedDeliveryTime) :
							new Date();
						this.initTimeSlots(date);
					});

					// 检查是否需要显示时间编辑图标
					this.showTimeEditIcon = this.deliveryMethods[this.selectedDeliveryIndex]?.dictValue === '2';
				} catch (error) {
					console.error('获取订单详情失败:', error);
				}
			},

			// 获取餐具状态字典
			async getDictsTableware(tableware) {
				try {
					const res = await getDicts(tableware);
					this.tablewareStatus = res.data;
				} catch (error) {
					console.error('获取餐具状态字典失败:', error);
				}
			},

			// 配送方式选择
			handleDeliveryMethodChange(e) {
				const index = e.detail.value;
				this.selectedDeliveryIndex = index;
				this.orderDetail.deliveryStatus = this.deliveryMethods[index].dictValue;
				this.showTimeEditIcon = this.deliveryMethods[index].dictValue === '2';

				// 如果切换到非'2'的配送方式，重置为默认时间
				if (!this.showTimeEditIcon) {
					const now = new Date();
					const defaultDeliveryTime = new Date(now.getTime() + 40 * 60 * 1000);
					this.setDefaultTimeSlot(defaultDeliveryTime);
				}
			},

			// 餐具状态选择
			handleTablewareStatusChange(value) {
				this.orderDetail.tablewareStatus = Number(value);
			},

			// 时间段选择处理
			handleTimeSlotChange(e) {
				const index = e.detail.value;
				this.selectedTimeSlotIndex = index;
				this.selectedTimeSlotText = this.timeSlots[index];
				this.orderDetail.estimatedDeliveryTime = this.timeRanges[index].start;
			},

			// 初始化时间段选择器
			initTimeSlots(time) {
				this.currentTime = time;
				const defaultDeliveryTime = new Date(time.getTime() + 40 * 60 * 1000);
				const slots = [];
				const ranges = [];

				// 生成未来6小时的时间段（每15分钟一段）
				for (let i = 0; i < 24; i++) {
					const start = new Date(defaultDeliveryTime.getTime() + i * 15 * 60 * 1000);
					const end = new Date(start.getTime() + 15 * 60 * 1000 - 1000);

					slots.push(`${this.formatTime(start)}-${this.formatTime(end)}`);
					ranges.push({
						start: this.formatDate(start),
						end: this.formatDate(end)
					});
				}

				this.timeSlots = slots;
				this.timeRanges = ranges;
				this.setDefaultTimeSlot(defaultDeliveryTime);
			},

			// 设置默认时间段
			setDefaultTimeSlot(time) {
				const index = this.timeRanges.findIndex(range => {
					const start = new Date(range.start);
					const end = new Date(range.end);
					return time >= start && time <= end;
				});

				if (index !== -1) {
					this.selectedTimeSlotIndex = index;
					this.selectedTimeSlotText = this.timeSlots[index];
					this.orderDetail.estimatedDeliveryTime = this.timeRanges[index].start;
				} else if (this.timeRanges.length > 0) {
					// 如果没有找到匹配的时间段，使用第一个时间段作为默认
					this.selectedTimeSlotIndex = 0;
					this.selectedTimeSlotText = this.timeSlots[0];
					this.orderDetail.estimatedDeliveryTime = this.timeRanges[0].start;
				}
			},

			// 格式化时间为 HH:mm
			formatTime(date) {
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			},

			// 格式化日期为 YYYY-MM-DD HH:mm:ss
			formatDate(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				const seconds = date.getSeconds().toString().padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},

			// 复制文本
			copyText(msg) {
				uni.setClipboardData({
					data: msg,
					success: () => Alert.success('复制成功'),
					fail: () => Alert.error('复制失败')
				});
			},

			// 提交支付订单
			async submit() {
				try {
					// 验证表单
					if (!this.validateForm()) return;

					// 提交订单
					await updateOrders(this.orderDetail);
					Alert.success("支付成功");
					uni.navigateBack({
						delta: 1
					});
				} catch (error) {
					Alert.error(error.message || "支付失败");
				}
			},

			// 验证表单
			validateForm() {
				// 1. 校验收货人姓名
				if (!this.orderDetail.receiverName?.trim()) {
					Alert.error("请输入收货人姓名/昵称");
					return false;
				}

				// 2. 校验手机号
				if (!this.orderDetail.receiverPhone?.trim()) {
					Alert.error("手机号不能为空");
					return false;
				} else if (this.orderDetail.receiverPhone.length !== 11) {
					Alert.error("请输入11位手机号");
					return false;
				}

				// 3. 校验收货地址
				if (!this.orderDetail.receiverAddress?.trim()) {
					Alert.error("请输入收货地址");
					return false;
				}

				// 4. 校验餐具数量
				if (this.orderDetail.tablewareStatus === 2) {
					if (!this.orderDetail.tablewareNumber || this.orderDetail.tablewareNumber === '') {
						Alert.error("请输入餐具数量");
						return false;
					} else if (isNaN(this.orderDetail.tablewareNumber) || this.orderDetail.tablewareNumber < 1) {
						Alert.error("餐具数量必须大于0");
						return false;
					}
				}

				return true;
			},

			// 检查只读模式
			checkReadOnlyMode() {
				// 可以在这里添加额外的只读模式逻辑
			}
		},

		// 导航栏渐变
		onPageScroll(e) {
			const scrollTop = e.scrollTop > 255 ? 255 : e.scrollTop;
			this.nav_opacity = `rgba(255,255,255,${scrollTop / 255})`;

			if (e.scrollTop > 20) {
				this.fontColor = '#000000';
				uni.setNavigationBarColor({
					frontColor: '#000000',
					backgroundColor: '#ffffff',
				});
			} else {
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: '#ffffff'
				});
				this.fontColor = '#ffffff';
			}
		}
	}
</script>
<style lang="scss">
	.content {
		color: #010101;
		font: normal 14px/2.2 Arial, Verdana, Tahoma, sans-serif;
		background-color: #F5F5F5;
	}

	.tang-feng-bg {
		width: 100%;
		height: 500rpx;
		position: relative;
		background: linear-gradient(to top, #ffffff, #118cff);
	}

	.tang-feng-block {
		padding: 20rpx;
		box-sizing: border-box;
		margin-top: -520rpx;
		position: relative;
		z-index: 3;

		.tang-feng-data {
			border-radius: 12rpx;
			margin-bottom: 20rpx;

			.detail-top {
				width: 100%;
				margin-bottom: 20rpx;

				.detail-top-1 {
					color: #ffffff;
					font-weight: bold;
					font-size: 46rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					image {
						width: 70rpx;
						height: 65rpx;
						margin-right: 10rpx;
					}
				}

				.detail-top-2 {
					color: #ffffff;
					font-size: 32rpx;
					text-align: center;
					letter-spacing: 3rpx;
					margin-top: 10rpx;
				}
			}

			.detailitem {
				background-color: #ffffff;
				border-radius: 20rpx;
				box-shadow: 0 0 6rpx rgba(0, 0, 150, 0.2);
				margin-bottom: 20rpx;
				padding: 15rpx;
				box-sizing: border-box;
			}

			.detail-address {
				display: flex;

				image {
					width: 40rpx;
					height: 40rpx;
					margin-right: 10rpx;
				}

				.top {
					width: 620rpx;
					font-weight: bold;
					letter-spacing: 3rpx;
					font-size: 32rpx;
					flex: 2;
					padding-right: 5rpx;
					align-items: center;
				}

				.address-textarea {
					width: 100%;
					min-height: 80rpx;
					margin-top: 10rpx;
				}
			}

			.shopBox {
				.item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 20rpx;

					image {
						width: 140rpx;
						height: 140rpx;
						border-radius: 10rpx;
					}

					.conBox {
						flex: 1;
						min-height: 140rpx;
						padding: 0 20rpx;
						box-sizing: border-box;
						display: flex;
						flex-direction: column;
						justify-content: space-between;

						.conBox-1 {
							font-size: 28rpx;
							font-weight: bold;
						}

						.conBox-3 {
							font-size: 34rpx;
							font-weight: bold;
							color: red;
						}
					}

					.number {
						width: 70rpx;
						text-align: center;
						font-size: 28rpx;
					}
				}
			}

			.orderItem {
				.orderItem-min {
					width: 100%;
					display: flex;
					align-items: center;
					letter-spacing: 4rpx;
					border-bottom: 2rpx solid #f3f3f3;
					padding: 15rpx 0;
					min-height: 60rpx;

					.orderItem-1 {
						width: 28%;
						color: rgba(0, 0, 0, 0.7);
						flex-shrink: 0;
					}

					.orderItem-2 {
						flex: 1;
						color: #000000;
						font-weight: bold;
						margin-right: 20rpx;
						word-break: break-word;
					}

					.orderItem-3 {
						padding: 0 20rpx;
						box-sizing: border-box;
						border-radius: 10rpx;
						background-color: #eeeeee;
						font-size: 24rpx;
					}
				}

				.orderInfo {
					justify-content: space-between;
				}

				.radio-container {
					display: flex;
					align-items: center;
					flex-wrap: wrap;
				}

				.radio-label {
					margin-right: 30rpx;
					display: flex;
					align-items: center;
					margin-bottom: 10rpx;
				}
			}
		}
	}
	.custom-radio {
	  display: flex;
	  align-items: center;
	}
	.custom-radio .radio-icon {
	  width: 36rpx;
	  height: 36rpx;
	  border-radius: 50%;
	  border: 2rpx solid #ccc;
	  margin: 0 15rpx;
	}
	.custom-radio.checked .radio-icon {
	  background-color: #019d3f;
	  border-color: #07C160;
	}
	.custom-radio.disabled {
	  opacity: 0.6;
	}

	.bottomBox {
		background-color: #ffffff;
		border: 1px solid #cccccc;
		box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.2);
		width: 750rpx;
		height: 140rpx;
		position: fixed;
		bottom: 0;
		z-index: 20;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 20rpx;
		box-sizing: border-box;
		letter-spacing: 5rpx;

		.leftTxt {
			color: #e55239;
			font-size: 40rpx;
			font-weight: bold;
		}

		.gnBox {
			height: 100%;
			display: flex;
			align-items: center;

			.item {
				background-color: #51baad;
				color: #ffffff;
				padding: 0 30rpx;
				box-sizing: border-box;
				margin-left: 15rpx;
				border-radius: 10rpx;
				height: 80rpx;
				line-height: 80rpx;
			}
		}
	}

	.input-item {
		width: 100%;
		height: 60rpx;
		margin-bottom: 15rpx;
		padding: 0 15rpx;
		border: 1rpx solid #eee;
		border-radius: 8rpx;

		&:last-child {
			margin-bottom: 0;
		}
	}

	.placeholder-style {
		color: #ccc;
		font-size: 28rpx;
	}
</style>